﻿using Basic.FormDAL.Model;
using Basic.FormModel.DB;
using SqlSugar;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Basic.FormDAL.Repository
{
    internal class TableGroupDAL : BasicDAL<DBTableGroup, long>, ITableGroupDAL
    {
        public TableGroupDAL ( IRepository<DBTableGroup> basicDAL ) : base(basicDAL)
        {
        }
        public int GetMaxSort ( long tableId, long groupId )
        {
            ISugarQueryable<MaxSortDto>[] tables = new ISugarQueryable<MaxSortDto>[]
            {
                this._BasicDAL.Queryable.Where(a=>a.TableId==tableId && a.ParentId==groupId).Select(a=>new MaxSortDto
                {
                    Sort=a.Sort
                }),
                this._BasicDAL.Provider.Queryable<DBTableColumn>().Where(a=>a.TableId==tableId && a.GroupId==groupId).Select(a=>new MaxSortDto
                {
                    Sort=a.Sort
                })
            };
            return this._BasicDAL.Provider.UnionAll<MaxSortDto>(tables).Max(a => a.Sort);
        }
        public long Add ( DBTableGroup data )
        {
            data.Id = IdentityHelper.CreateId();
            this._BasicDAL.Insert(data);
            return data.Id;
        }
        public void SetSort ( KeyValuePair<long, int>[] sort )
        {
            ISqlQueue<DBTableGroup> queue = this._BasicDAL.BeginQueue();
            sort.ForEach(c =>
            {
                queue.UpdateOneColumn(a => a.Sort == c.Value, a => a.Id == c.Key);
            });
            _ = queue.Submit();
        }
    }
}
